package cn.edu.ctbu.sbadmin.system.shiro;

import cn.edu.ctbu.sbadmin.common.config.ApplicationContextRegister;
import cn.edu.ctbu.sbadmin.common.utils.UserType;
import cn.edu.ctbu.sbadmin.grade.domain.StudentDO;
import cn.edu.ctbu.sbadmin.grade.service.StudentService;
import cn.edu.ctbu.sbadmin.system.service.MenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class StudentRealm extends AuthorizingRealm {
    /**
     * 获取登录用户的授权信息
     * @param arg0
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0){

        Subject subject = SecurityUtils.getSubject();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if(subject.getPrincipal() instanceof StudentDO){
            System.out.println("StudentRealm 执行授权逻辑");
            StudentDO user = (StudentDO) subject.getPrincipal();
            MenuService menuService = ApplicationContextRegister.getBean(MenuService.class);
            Set<String> perms = menuService.listPermsByRoleName("Student");

            info.setStringPermissions(perms);

        }
        return info;
    }

    /**
     * 认证
     * @param userToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken userToken)throws AuthenticationException{

        UsernamePasswordToken token = (UsernamePasswordToken) userToken;

        String username = (String) token.getPrincipal();
        Map<String,Object> map = new HashMap<>(16);
        map.put("username",username);
        String password = new String((char[]) token.getCredentials());
        StudentService teacherService = ApplicationContextRegister.getBean(StudentService.class);

        List<StudentDO> byUserName = teacherService.getByUserName(username);
        StudentDO user = null;
        if(byUserName.size()>0){
            user = byUserName.get(0);
        }

        if(user == null){
            throw new UnknownAccountException("账号或密码不正确");
        }

        if(!password.equals(user.getPassword())){
            throw new IncorrectCredentialsException("账号或密码不正确");
        }

        if(user.getIsDeleted() > 0){
            throw new LockedAccountException("账号已被锁定，请联系管理员");
        }
        user.setUserType(UserType.Student());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,password,getName());
        return info;
    }

}
